package com.mojian.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mojian.entity.SysTag;
import com.mojian.service.ArticleService;
import com.mojian.service.TagService;
import com.mojian.vo.article.ArticleListVo;
import com.mojian.vo.tag.TagListVo;
import com.mojian.mapper.SysTagMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@RequiredArgsConstructor
public class TagServiceImpl implements TagService {

    private final SysTagMapper sysTagMapper;

    @Resource
    private ArticleService articleService;

    @Override
    public List<TagListVo> getTagsApi(Integer categoryId) {
        if (categoryId == null) {
            return sysTagMapper.getTagsApi();
        } else {
            IPage<ArticleListVo> articleList = articleService.getArticleList(null, categoryId, null);
            List<ArticleListVo> records = articleList.getRecords();

            Set<Long> uniqueTagIds = new HashSet<>();
            List<TagListVo> tagList = new ArrayList<>();
            Map<Long, Integer> tagCountMap = new HashMap<>();

            for (ArticleListVo record : records) {
                Long articleId = record.getId();
                List<Integer> tagIdsByArticleId = sysTagMapper.getTagIdsByArticleId(Math.toIntExact(articleId));

                for (Integer tagId : tagIdsByArticleId) {
                    Long tagIdLong = tagId.longValue();

                    if (uniqueTagIds.contains(tagIdLong)) {
                        tagCountMap.put(tagIdLong, tagCountMap.get(tagIdLong) + 1);
                        continue;
                    }

                    uniqueTagIds.add(tagIdLong);
                    tagCountMap.put(tagIdLong, 1);

                    SysTag tag = sysTagMapper.selectById(tagIdLong);

                    TagListVo tagListVo = new TagListVo();
                    tagListVo.setId(Math.toIntExact(tagIdLong));
                    tagListVo.setName(tag.getName());
                    tagListVo.setArticleNum(tagCountMap.get(tagIdLong));

                    tagList.add(tagListVo);
                }
            }

            return tagList;
        }
    }

}
